package system

import (
	"cubeAdmin/common"
	"cubeAdmin/common/jwtauth"
	"cubeAdmin/common/utils"
	"cubeAdmin/common/utils/gconv"
	"cubeAdmin/controllers"
	"cubeAdmin/dto"
	"cubeAdmin/models"
	"encoding/json"
	"fmt"
	"github.com/beego/beego/v2/core/logs"
	"github.com/beego/beego/v2/core/validation"
)

// UserController 用户 API
type UserController struct {
	controllers.BaseController
}

func (c *UserController) URLMapping() {
	c.Mapping("Post", c.Post)
	c.Mapping("GetAll", c.GetAll)
	c.Mapping("Put", c.Put)
	c.Mapping("Delete", c.Delete)
}

// Index 获取用户列表视图
// @router /index [get]
func (c *UserController) Index() {
	c.Data["pageTitle"] = "用户列表"
	user, _ := jwtauth.GetAdminDetailUser(c.Ctx.Input)
	c.Data["user"] = user
	c.TplName = "system/user/main.tpl"
}

// GetAll @Title 用户列表
// @Description 用户列表
// @Success 200 {object} controllers.Result
// @router / [get]
func (c *UserController) GetAll() {
	deptId, _ := c.GetInt64("deptId", -1)
	enabled, _ := c.GetInt64("enabled", -1)
	getString := c.GetString("nickName")
	total, list := models.GetAllUser(c.GetParams(), deptId, enabled, getString)
	c.PageTable(gconv.Int64(total), list)
}

// Post @Title 用户添加
// @Description 用户添加
// @Success 200 {object} controllers.Result
// @router / [post]
func (c *UserController) Post() {
	var model models.SysUser
	valid := validation.Validation{}
	json.Unmarshal(c.Ctx.Input.RequestBody, &model)
	b, _ := valid.Valid(&model)
	if !b {
		for _, err := range valid.Errors {
			c.Fail(err.Message, 5001)
		}
	}
	_, e := models.AddUser(&model)
	if e != nil {
		c.Fail(e.Error(), 5002)
	}
	c.Ok("操作成功")
}

// Add 用户添加页面
// @router /add [get]
func (c *UserController) Add() {
	list := models.GetRoleList()
	jobList := models.GetAllJobList()
	c.Data["RolesList"] = list
	c.Data["JobList"] = jobList
	c.TplName = "system/user/add.tpl"
}

// Put @Title 用户编辑
// @Description 用户编辑
// @Success 200 {object} controllers.Result
// @router / [put]
func (c *UserController) Put() {
	var model models.SysUser
	valid := validation.Validation{}
	json.Unmarshal(c.Ctx.Input.RequestBody, &model)

	logs.Info("======start======")
	logs.Info(model)
	b, _ := valid.Valid(&model)
	if !b {
		for _, err := range valid.Errors {
			c.Fail(err.Message, 5003)
		}
	}
	e := models.UpdateByUser(&model)
	if e != nil {
		c.Fail(e.Error(), 5004)
	}
	c.Ok("操作成功")
}

// UpdateByIdAndEnabled 更新启用状态
// @router /enabled [put]
func (c *UserController) UpdateByIdAndEnabled() {
	var model dto.UserEnabled
	json.Unmarshal(c.Ctx.Input.RequestBody, &model)
	e := models.UpdateUserByIdAndEnabled(model.Id, model.Enabled)
	if e != nil {
		c.Fail(e.Error(), 5004)
	}
	c.Ok("操作成功")
}

// Edit 跳转到用户编辑
// @router /edit [get]
func (c *UserController) Edit() {
	uid, _ := c.GetInt64("id")
	user, _ := models.GetUserById(uid)
	list := models.GetRoleList()
	c.Data["title"] = "用户修改"
	c.Data["user"] = user

	jobList := models.GetAllJobList()
	c.Data["JobList"] = jobList

	ar := make([]map[string]interface{}, 0)
	for _, role := range list {
		m := make(map[string]interface{})

		m["id"] = role.Id
		m["name"] = role.Name
		m["checked"] = false

		for _, r := range user.Roles {
			if role.Id == r.Id {
				m["checked"] = true
			}
		}

		ar = append(ar, m)
	}

	c.Data["RolesList"] = ar
	fmt.Println(ar)

	c.TplName = "system/user/edit.tpl"
}

// Delete @Title 用户删除
// @Description 用户删除
// @Success 200 {object} controllers.Result
// @router / [delete]
func (c *UserController) Delete() {
	var ids []int64
	json.Unmarshal(c.Ctx.Input.RequestBody, &ids)
	e := models.DelByUser(ids)
	if e != nil {
		c.Fail(e.Error(), 5005)
	}
	c.Ok("操作成功")
}

// Avatar @Title 用户上传图像
// @Description 用户上传图像
// @Success 200 {object} controllers.Result
// @router /updateAvatar [put]
func (c *UserController) Avatar() {
	avatarUrl := c.GetString("key")
	uid, _ := jwtauth.GetAdminUserId(c.Ctx.Input)
	user, _ := models.GetUserById(uid)
	if user == nil {
		c.Fail("操作失败", common.DatabaseOperationErr)
	} else {
		user.Avatar = avatarUrl
		models.UpdateCurrentUser(user)
		c.Ok("操作成功")
	}
}

// Pass @Title 用户修改密码
// @Description 用户修改密码
// @Success 200 {object} controllers.Result
// @router /updatePass [post]
func (c *UserController) Pass() {
	var model dto.UserPass
	valid := validation.Validation{}
	json.Unmarshal(c.Ctx.Input.RequestBody, &model)
	b, _ := valid.Valid(&model)
	if !b {
		for _, err := range valid.Errors {
			c.Fail(err.Message, 5007)
		}
	}
	//save user
	uid, _ := jwtauth.GetAdminUserId(c.Ctx.Input)
	user, e := models.GetUserById(uid)
	if e != nil {
		c.Fail("信息查询失败", common.DatabaseOperationErr)
	} else {
		if !utils.ComparePwd(user.Password, []byte(model.OldPass)) {
			c.Fail("旧密码错误密码错误", 5009)
		}
		user.Password = utils.HashAndSalt([]byte(model.NewPass))
		models.UpdateCurrentUser(user)
		c.Ok("ok")
	}
}

// Center @Title 用户修改个人信息
// @Description 用户修改个人信息
// @Success 200 {object} controllers.Result
// @router /center [put]
func (c *UserController) Center() {
	var model dto.UserPost
	valid := validation.Validation{}
	json.Unmarshal(c.Ctx.Input.RequestBody, &model)
	b, _ := valid.Valid(&model)
	if !b {
		for _, err := range valid.Errors {
			c.Fail(err.Message, common.ArgsValidErr)
		}
	}
	//save user
	uid, _ := jwtauth.GetAdminUserId(c.Ctx.Input)
	user, e := models.GetUserById(uid)
	if e != nil {
		c.Fail("查询用户失败", common.DatabaseOperationErr)
	} else {
		user.Phone = model.Phone
		user.Sex = model.Sex
		user.NickName = model.NickName
		err := models.UpdateCurrentUser(user)
		if err != nil {
			logs.Error(err.Error())
		}
		//更新用户信息到缓存
		err1 := jwtauth.UpdateSession(c.Ctx.Input)
		if err1 != nil {
			logs.Error(err1.Error())
		}
		c.Ok("ok")
	}
}

// CenterIndex 跳转 用户个人信息
// @router /center [get]
func (c *UserController) CenterIndex() {
	user, _ := jwtauth.GetAdminDetailUser(c.Ctx.Input)
	c.Data["user"] = user
	c.Data["title"] = "个人中心"
	c.TplName = "system/user/center.tpl"
}

// Profile 跳转图片截取页面
// @router /profile [get]
func (c *UserController) Profile() {
	user, _ := jwtauth.GetAdminDetailUser(c.Ctx.Input)
	c.Data["user"] = user
	c.Data["title"] = "更换头像"
	c.TplName = "system/user/profile.tpl"
}
